package cn.hd01.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.domain.Specifications;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import cn.hd01.repository.CustomerBankCardRepository;
import cn.hd01.repository.entity.Customer;
import cn.hd01.repository.entity.CustomerBankCard;
import cn.hd01.service.CustomerBankCardService;

@Service
public class CustomerBankCardServiceImpl extends BaseServiceImpl<CustomerBankCard, Integer> implements CustomerBankCardService {

	private CustomerBankCardRepository repository;

	@Autowired
	public CustomerBankCardServiceImpl(CustomerBankCardRepository repository) {
		super(repository);
		this.repository = repository;
	}

	@Override
	public List<CustomerBankCard> findByCustomerId(Integer customerId) {
		return repository.findByCustomerId(customerId);
	}

	@Override
	public CustomerBankCard findByDefaultCard(Integer customerId) {
		return repository.findByCustomerIdAndIsDefault(customerId, true);
	}

	@Override
	public Page<CustomerBankCard> findAll(final CustomerBankCard customerBankCard,
			Pageable pageable) {
		if (customerBankCard == null) {
			return repository.findAll(pageable);
		}

		return repository.findAll(Specifications.where(new Specification<CustomerBankCard>() {
			@Override
			public Predicate toPredicate(Root<CustomerBankCard> r, CriteriaQuery<?> q, CriteriaBuilder cb) {
				List<Predicate> predicates = new ArrayList<Predicate>();

				if (customerBankCard.getCustomerId() != null) {
					predicates.add(cb.equal(r.get("customerId").as(String.class), customerBankCard.getCustomerId()));
				}

				return cb.and(predicates.toArray(new Predicate[] {}));
			}
		}), pageable);
	}

	@Override
	public void deleteByCustomerId(Integer customerId) {
		repository.deleteByCustomerId(customerId);
	}

}
